﻿using EONFULLSIN2.Common;
using EONFULLSIN2.Core.EventArgs;
using EONFULLSIN2.Services.ControlService;
using EONFULLSIN2.Services.DB;
using EONFULLSIN2.Services.Device.JuYing;
using EONFULLSIN2.Services.Device.ZhongChuangZhiHe;
using EONFULLSIN2.Services.Device.ZhuoLan;
using EONFULLSIN2.Services.Device.ZMoiton;
using EONFULLSIN2.Services.Message;
using EONFULLSIN2.ViewModelBase;
using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace EONFULLSIN2.ViewModel {

    public class DeviceControlViewModel : NavigationViewModel {

        private readonly IMessageService _messageService;
        private readonly IJuYingModbusService _juYingModbusService;
        private readonly IZhuoLanModbusService _zhuoLanModbusService;
        private readonly IZMoitonService _zMoitonService;
        private readonly IZczhModbusService _zczhModbusService;
        private readonly ITempNegative80Service _tempNegative80Service;
        private readonly System.Timers.Timer _spendTimer;
        protected readonly DateTime _spendTime = new DateTime(0);
        public DeviceControlViewModel(
            IRegionManager regionManager, 
            IDialogService dialog, 
            IMessageService messageService, 
            IEventAggregator eventAggregator,
            IDbOperate<IFreeSqlMainContext> mainDbOperate,
            IJuYingModbusService juYingModbusService,
            IZhuoLanModbusService zhuoLanModbusService,
            IZMoitonService zMoitonService,
            IZczhModbusService zczhModbusService,
            ITempNegative80Service tempNegative80Service)
            : base(regionManager, dialog, messageService, eventAggregator, mainDbOperate) {

            this._messageService = messageService;

            this._juYingModbusService = juYingModbusService;
            this._zhuoLanModbusService = zhuoLanModbusService;
            this._zMoitonService = zMoitonService;
            this._zczhModbusService = zczhModbusService;
            this._tempNegative80Service = tempNegative80Service;
            _tempNegative80Service.RunStepEvent += _tempNegative80Service_RunStepEvent;


            WaitTime = _spendTime;
            _spendTimer?.Stop();
            _spendTimer?.Close();
            _spendTimer?.Dispose();
            _spendTimer = new System.Timers.Timer {
                Interval = 1000
            };
            _spendTimer.Elapsed += (s, e) => {
                if (App.Current != null) {
                    App.Current.Dispatcher.InvokeAsync(() => {
                        WaitTime = WaitTime.Value.AddSeconds(1);
                    });
                }
            };
        }

        #region Props

        private string _logText = "";

        public string LogText {
            get { return _logText; }
            set { _logText = value; base.RaisePropertyChanged(); }
        }

        private bool _isCheckOk = false;

        public bool IsCheckOk {
            get { return _isCheckOk; }
            set { _isCheckOk = value; base.RaisePropertyChanged(); }
        }

        private string _stepName = "";

        public string StepName {
            get { return _stepName; }
            set { _stepName = value; base.RaisePropertyChanged(); }
        }

        private DateTime? _waitTime;

        public DateTime? WaitTime {
            get { return _waitTime; }
            set { _waitTime = value; base.RaisePropertyChanged(); }
        }
        #endregion


        #region Commands
        /// <summary>
        /// 开始自检
        /// </summary>
        public DelegateCommand<TcpModbusItemsDto> StartSelfCheckCmd => new DelegateCommand<TcpModbusItemsDto>(async (obj) => {
            StepName = "正在自检中...";
            IsCheckOk = false;
            try {
                var sensorData = await _juYingModbusService.GetSensorDataAsync();
                var defrostStatus = await _zczhModbusService.GetSensorDataAsync();
                var sensorListData = new List<Models.Dto.Device.SensorItemDto>();
                sensorListData.AddRange(sensorData);
                sensorListData.AddRange(defrostStatus);
                if (sensorListData != null && sensorListData.Count > 0) {
                    foreach (var item in sensorListData) {
                        bool isOk = false;//自检结果
                        string sNumber = item.CodeNumber;
                        string sDesc = item.Description;
                        double sVal = Convert.ToDouble(item.Value);
                        string message = string.Empty;

                        switch (item.Type) {
                            case Models.Enum.eSensorTypeEnum.Temperature:
                                isOk = (sVal <= 35.0);
                                break;
                            case Models.Enum.eSensorTypeEnum.Pressure:
                                isOk = (sVal <= 15);
                                break;
                            case Models.Enum.eSensorTypeEnum.Voltage:
                                isOk = (sVal <= 0);
                                if (sNumber == "V50001") {//门磁开关电压
                                    isOk = (sVal >= 200);
                                }
                                break;
                            case Models.Enum.eSensorTypeEnum.Current:
                                break;
                            default:
                                break;
                        }
                        _tempNegative80Service_RunStepEvent(null, new MessageEventArgs($"自检结果[{isOk}]，传感器[{item.CodeNumber}-{item.Description}]数值异常，当前值：{sVal}"));
                    }
                }
                IsCheckOk = true;
            } catch (Exception ex) {
                _messageService.Error(ex.Message);
            }
            StepName = $"自检完成，自检结果：{IsCheckOk}";
        });

        /// <summary>
        /// 双机组运行
        /// </summary>
        public DelegateCommand<TcpModbusItemsDto> TwoUnitStartCmd => new DelegateCommand<TcpModbusItemsDto>((obj) => {

            _ = _tempNegative80Service.PreCoolingCoolingStartAsync();

        });

        /// <summary>
        /// 单机组运行
        /// </summary>
        public DelegateCommand<TcpModbusItemsDto> OneUnitStartCmd => new DelegateCommand<TcpModbusItemsDto>((obj) => {

            _ = _tempNegative80Service.LowTemperatureStandbyStartAsync();

        });

        /// <summary>
        /// 双机组关机
        /// </summary>
        public DelegateCommand<TcpModbusItemsDto> TwoUnitShutDownCmd => new DelegateCommand<TcpModbusItemsDto>((obj) => {

            _ = _tempNegative80Service.ShutdownWarmingStartAsync();

        });

        /// <summary>
        /// 除霜启动
        /// </summary>
        public DelegateCommand<TcpModbusItemsDto> DefrostStartCmd => new DelegateCommand<TcpModbusItemsDto>((obj) => {

            _ = _tempNegative80Service.DefrostStartAsync();

        });

        /// <summary>
        /// 除霜停止
        /// </summary>
        public DelegateCommand<TcpModbusItemsDto> DefrostStopCmd => new DelegateCommand<TcpModbusItemsDto>((obj) => {

            _ = _tempNegative80Service.DefrostStopAsync();

        });

        /// <summary>
        /// 舱内干燥启动
        /// </summary>
        public DelegateCommand<TcpModbusItemsDto> DryStartCmd => new DelegateCommand<TcpModbusItemsDto>((obj) => {

            //_ = _tempNegative80Service.CabinDryStartAsync();

        });

        /// <summary>
        /// 舱内干燥关闭
        /// </summary>
        public DelegateCommand<TcpModbusItemsDto> DryStopCmd => new DelegateCommand<TcpModbusItemsDto>((obj) => {

            //_ = _tempNegative80Service.CabinDryStopAsync();

        });
        #endregion

        #region Methods
        private void _tempNegative80Service_RunStepEvent(object? sender, EventArgs e) {

            var args = e as MessageEventArgs;

            LogText += $"{args?.HappendDate.ToString("yyyy-MM-dd HH:mm:ss")} => {args?.Message}{Environment.NewLine}";

            if (!string.IsNullOrEmpty(args?.StepName)) {
                StepName = args.StepName;
            }

            if ((args?.Data.ContainsKey("WaitTime")).Value) {
                _spendTimer?.Stop();
                WaitTime = _spendTime;
                _spendTimer?.Start();
            }
        }
        #endregion



    }
}
